package com.raymond.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2020-05-26 15:35
 */

@Configuration
@EnableAsync
@ConfigurationProperties(prefix = "thread.pool")
@Data
public class ThreadPoolConfig {
    /** 核心线程数（默认线程数）*/
    private  int corePoolSize;
    /** 最大线程数 */
    private  int maxPoolSize;
    /** 允许线程空闲时间（单位：默认为秒）*/
    private  int keepAliveTime;
    /** 缓冲队列数 */
    private  int queueCapacity;

    @Bean
    public ThreadPoolTaskExecutor threadExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("async-service-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
